package ge.telasi.tasks.ui.comp;

import ge.telasi.tasks.ui.UIUtils;
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;

/**
 * @author dimitri
 */
public class Navigator extends JPanel {
    Hyperlink lnkPrevious;
    Hyperlink lnkNext;
    JLabel lblStatus;
    PageableTable<?> table;

    public Navigator() {
        initComponents();
    }

    private void initComponents() {
        setLayout(new BorderLayout(5, 5));
        lnkPrevious = new Hyperlink("< წინა") {
            @Override
            public void onClick() {
                table.previous();
            }
        };
        lnkNext = new Hyperlink("შემდეგი >") {
            @Override
            public void onClick() {
                table.next();
            }
        };
        lblStatus = new JLabel("--location--");
        lblStatus.setFont(UIUtils.makeBold(lblStatus.getFont()));
        lblStatus.setHorizontalAlignment(JLabel.CENTER);
        add(lnkPrevious, BorderLayout.WEST);
        add(lnkNext, BorderLayout.EAST);
        add(lblStatus, BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    }

    public PageableTable<?> getTable() {
        return table;
    }

    public void setTable(PageableTable<?> table) {
        this.table = table;
        table.getModel().addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                reset();
            }
        });
    }

    public void reset() {
        if (table != null) {
            int page = table.getPage();
            int maxPage = table.getMaxPage();
            if (page > maxPage) {
                lnkNext.setVisible(false);
                lnkPrevious.setVisible(false);
                if (maxPage == -1) {
                    lblStatus.setText("0 - 0 სულ 0-დან");
                } else {
                    lblStatus.setText("");
                }
            } else {
                boolean firstPage = table.isFirstPage();
                boolean lastPage = table.isLastPage();
                int perPage = table.getPerPage();
                int total = table.getTotalCount();
                int from = page * perPage + 1;
                int to = from + table.getRowCount() - 1;
                lnkPrevious.setVisible(!firstPage);
                lnkNext.setVisible(!lastPage);
                lblStatus.setText(from + " - " + to + ",  სულ " + total + "-დან");
            }
        } else {
            lnkNext.setVisible(false);
            lnkPrevious.setVisible(false);
            lblStatus.setText("");
        }
    }

}
